/**
 * @file file_read_write_demo.c
 * @author binwangn (you@domain.com)
 * @brief 
 * @version 0.1
 * @date 2023-11-28
 * 
 * @copyright Copyright (c) 2023
 * 
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STU_CNT 4

typedef struct 
{
    char m_name[16];
    int m_num;
    int m_age;
    char m_addr[32];
}STU_INFO;

/**
 * @brief 将传入的信息写入指定文件中
 * @param stu_info  待写入文件的信息（数组）
 * @param stu_cnt   待写入信息元素个数（数组成员个数）
 * @param file_path 待写入文件路径
 * @return -1   文件打开失败
 * @return int  写入的信息元素个数
 **/
int store_info(const STU_INFO *stu_info, unsigned long stu_cnt, const char* file_path)
{
    FILE *stu_file = fopen(file_path, "ab");
    if (stu_file == NULL)
    {
        return -1;
    }

    size_t w_cnt = fwrite(stu_info, sizeof(STU_INFO), stu_cnt, stu_file);
    fclose(stu_file);
    
    return w_cnt;
}

/**
 * @brief 从指定文件中读取信息到指定的内存空间
 * @param stu_info  读取后的信息存入的内存空间地址
 * @param stu_cnt   待读取的信息元素个数
 * @param file_path 待读取的文件路径
 * @return -1   文件打开失败
 * @return int  实际读取的信息元素个数
 */
int get_info(STU_INFO *stu_info, unsigned long stu_cnt, const char* file_path)
{
    FILE *stu_file = fopen(file_path, "rb");
    if (stu_file == NULL)
    {
        return -1;
    }

    size_t r_cnt = fread(stu_info, sizeof(STU_INFO), stu_cnt, stu_file);
    fclose(stu_file);

    return r_cnt;
}

int main(int argc, char *args[], ...)
{
    // 从控制台录入学生信息，并存入数组students_info中
    STU_INFO students_info[STU_CNT];
    for (int stu_idx = 0; stu_idx < STU_CNT; ++stu_idx) 
    {
        printf("Please input the student %d information with the order: name, number, age, address\n", stu_idx);
        scanf("%s %d %d %s", students_info[stu_idx].m_name, 
                &students_info[stu_idx].m_num,
                &students_info[stu_idx].m_age,
                students_info[stu_idx].m_addr);
    }

    // 创建存储学生信息的文件
    FILE *stu_info_file = fopen("D:\\studentinfo.bin", "wb");
    int ret = fclose(stu_info_file);
    if (ret == EOF)
    {
        printf("Close file failed.%s:%d", __FILE__, __LINE__);
    }

    // 将学生信息写入文件 D:\studentinfo.dat
    store_info(students_info, 4, "D:\\studentinfo.bin");

    // 从文件 D:\studentinfo.dat 中读取学生信息
    memset(students_info, 0, sizeof(students_info));
    int r_cnt = get_info(students_info, STU_CNT, "D:\\studentinfo.bin");

    // 输出读取结果到控制台
    printf("name\tnumber\t\tage\taddress\n----------------------------------------------------------\n");
    for (int stu_idx = 0; stu_idx < STU_CNT; ++stu_idx)
    {
        printf("%s\t%d\t%d\t%s\n", students_info[stu_idx].m_name, students_info[stu_idx].m_num, students_info[stu_idx].m_age, students_info[stu_idx].m_addr);
    }

    return 0;
}
